package com.zdsoft.crm.controller.product;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.zdsoft.crm.controller.BaseController;
import com.zdsoft.crm.entity.Clue;
import com.zdsoft.crm.entity.auth.SysFunction;
import com.zdsoft.crm.entity.product.Product;
import com.zdsoft.crm.entity.product.ProductType;
import com.zdsoft.crm.service.product.IProductService;
import com.zdsoft.crm.util.DateUtil;
import com.zdsoft.crm.util.UuidKit;
import com.zdsoft.crm.vo.AjaxVo;
import com.zdsoft.crm.vo.PageVo;
import com.zdsoft.crm.vo.product.ProductListVo;
import com.zdsoft.crm.vo.product.ProductTypeVo;

@Controller
@RequestMapping("/product")
public class ProductController extends BaseController{

	@Autowired
	IProductService productService;
	
	@Autowired
	HttpSession session;
	
	@GetMapping("/list")
	public ModelAndView product(@RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize) {
		PageVo list = productService.findPage(pageNum, pageSize);
		
		return new ModelAndView("/product/list.html", "list", list);
	}
	
	@GetMapping("/saveUI")
	public 	ModelAndView saveUI(){
		
		
		return new ModelAndView("/product/save.html","pt",productService.findAll());
	}
	
	@GetMapping("/saveType")
	public 	String saveType(){
		return "/product/saveType.html";
	}
	
	@PostMapping("/saveType")
	@ResponseBody
	public 	AjaxVo saveProductType(@Valid ProductTypeVo productTypeVo,BindingResult result){
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				return new AjaxVo().setErrorCode("10002").setErrorMsg(error.getDefaultMessage());
			}
		}
		
		ProductType productType=new ProductType();
		String typeName=productTypeVo.getTypeName();
		ProductType pro=productService.findByTypeName(typeName);
		if(pro==null){
			productType.setTypeName(productTypeVo.getTypeName());
			productType.setTypeInfo(productTypeVo.getTypeInfo());
			productService.saveType(productType);
			return new AjaxVo().setErrorCode("0").setErrorMsg("添加成功");
		}
		return new AjaxVo().setErrorCode("10002").setErrorMsg("产品类别已存在");
		
	}
	
		/**
		 * MultipartFile file 页面传送过来的文件
		 * 
		 * @param file
		 * @return
		 * @throws IOException
		 * @throws IllegalStateException
		 */
		@PostMapping("/mastermap")
		@ResponseBody
		public AjaxVo upload(MultipartFile file) throws IllegalStateException, IOException {
			// 获取文件后缀
			System.out.println(file.getOriginalFilename());
			// 生成文件名
			String fileName = UuidKit.uuid() + "." + FilenameUtils.getExtension(file.getOriginalFilename());
			
			String uploadPath = session.getServletContext().getRealPath("/upload");
			File newFile = new File(uploadPath + File.separatorChar + fileName);
			if (!newFile.exists())
				newFile.createNewFile();
			// 保存文件
			file.transferTo(newFile);
			return new AjaxVo().setErrorCode("0").setData(fileName);
		}

		
		@PostMapping("/picture")
		@ResponseBody
		public AjaxVo uploadPicture(MultipartFile file) throws IllegalStateException, IOException {
			// 获取文件后缀
			System.out.println(file.getOriginalFilename());
			// 生成文件名
			String fileName = UuidKit.uuid() + "." + FilenameUtils.getExtension(file.getOriginalFilename());
			
			String uploadPath = session.getServletContext().getRealPath("/upload");
			File newFile = new File(uploadPath + File.separatorChar + fileName);
			if (!newFile.exists())
				newFile.createNewFile();
			// 保存文件
			file.transferTo(newFile);
			return new AjaxVo().setErrorCode("0").setData(fileName);
		}
	
	
	@PostMapping("/saveUI")
	@ResponseBody
	public AjaxVo save(@Valid ProductListVo productListVo,BindingResult result){
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				return new AjaxVo().setErrorCode("10002").setErrorMsg(error.getDefaultMessage());
			}
		}
		Product prod=new Product();
		prod.setProductName(productListVo.getProductName());
		prod.setProduct_type_id(productListVo.getProduct_type_id());
		prod.setCreate_time(DateUtil.toDate(productListVo.getCreate_time()));
		prod.setProduct_URL(productListVo.getProduct_URL());
		prod.setTeam(productListVo.getTeam());
		prod.setCost_price(productListVo.getCost_price());
		prod.setList_price(productListVo.getList_price());
		prod.setMaster_map(productListVo.getMaster_map());
		prod.setProduct_info(productListVo.getProduct_info());
		prod.setPicture(productListVo.getPicture());
		productService.save(prod);
		return new AjaxVo().setErrorCode("0").setErrorMsg("添加成功");
	}
	
	@DeleteMapping("/delete")
	@ResponseBody // ajax提交时必须需要加的注解
	public void deleteAll(@RequestBody String idsStr) {
		System.out.println(idsStr);
		String[] list=idsStr.split(",");
		if(list.length!=0){
			for (String string : list) {
				productService.delete(string);
			}
		}
	}
	
	@GetMapping("/getInfo")
	public ModelAndView getInfo(String id) {
		Product products=productService.getProductInfo(id);
		String typeId=products.getProduct_type_id();
		ProductType productType=productService.findTypeInfo(typeId);
		String typeName = productType.getTypeName();
		
		ModelAndView mav = new ModelAndView("/product/info.html");
		Product product=productService.getProductInfo(id);
		mav.addObject("typeName", typeName);
		mav.addObject("product", product);
		String productURL=product.getProduct_URL();
		if(!StringUtils.isEmpty(productURL)){
			mav.addObject("productURL", productURL);//详情链接

		}else{
			mav.addObject("productURL", "无");//详情链接
		}
		if(product.getMaster_map()==null){
			mav.addObject("picture", new String(""));
		}else{
			mav.addObject("picture", new String(product.getMaster_map()));
		}
		if(product.getPicture()==null){
			mav.addObject("picture", new String(""));//副图
		}else{
			mav.addObject("picture", new String(product.getPicture()));//副图
		}
		mav.addObject("remark", new String(product.getProduct_info()));//备注
		

		return mav;
	}
	
	@GetMapping("/updateUI/{id}")
	public ModelAndView updateUI(@PathVariable("id") String id){
		Product pro=productService.finInfo(id);
		ModelAndView mav=new ModelAndView("/product/update.html");
		mav.addObject("list", pro);
		mav.addObject("pt", productService.findAll());
		return mav;
	}
	
	@PostMapping("/updateUI/{id}")
	@ResponseBody
	public AjaxVo update(@Valid ProductListVo productListVo,BindingResult result,String product_type_id){
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				return new AjaxVo().setErrorCode("10002").setErrorMsg(error.getDefaultMessage());
			}
		}
		
		Product pro=new Product();
		pro.setId(productListVo.getId());
		pro.setProductName(productListVo.getProductName());
		pro.setProduct_type_id(productService.findByTypeName(product_type_id).getId());
		pro.setCreate_time(DateUtil.toDate(productListVo.getCreate_time()));
		pro.setProduct_URL(productListVo.getProduct_URL());
		pro.setTeam(productListVo.getTeam());
		pro.setCost_price(productListVo.getCost_price());
		pro.setList_price(productListVo.getList_price());
		pro.setMaster_map(productListVo.getMaster_map());
		pro.setProduct_info(productListVo.getProduct_info());
		pro.setPicture(productListVo.getPicture());
		productService.update(pro);
		return new AjaxVo().setErrorCode("0").setErrorMsg("修改成功");
	}
	
	@GetMapping("/listLoyer")
	public ModelAndView list(@RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(name = "pageSize", defaultValue = "4") Integer pageSize,
			@RequestParam(name = "typeName", defaultValue = "") String typeName) throws UnsupportedEncodingException {
		
		// Get 中文请求处理,解决查询乱码问题
		typeName = new String(typeName.getBytes("ISO8859-1"), "UTF-8");

		ModelAndView mav = new ModelAndView("/product/listLoyer.html", "list",
				productService.findPageType(pageNum, pageSize, typeName));
		mav.addObject("typeName", typeName);
		return mav; // 省代码(视图解析器)
	}
	
	@GetMapping("/listInfo")
	public void listInfo(String typeName) {
		System.out.println(typeName);
		 // 省代码(视图解析器)
	}
	
	@GetMapping("/list1")
	public ModelAndView product(@RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize,
			@RequestParam(name = "typeName", defaultValue = "") String typeName) throws UnsupportedEncodingException {
		
		
		// Get 中文请求处理,解决查询乱码问题
		typeName = new String(typeName.getBytes("ISO8859-1"), "UTF-8");
		ProductType productType=productService.findByTypeName(typeName);
		String product_type_id=productType.getId();
		ModelAndView mav = new ModelAndView("/product/list.html", "list",
				productService.pageList1(pageNum, pageSize, product_type_id));
		mav.addObject("product_type_id", product_type_id);
		return mav; // 省代码(视图解析器)
	}
	
	@GetMapping("/listType")
	public ModelAndView listType(@RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(name = "pageSize", defaultValue = "4") Integer pageSize,
			@RequestParam(name = "typeName", defaultValue = "") String typeName) throws UnsupportedEncodingException {
		
		// Get 中文请求处理,解决查询乱码问题
		typeName = new String(typeName.getBytes("ISO8859-1"), "UTF-8");

		ModelAndView mav = new ModelAndView("/product/listType.html", "list",
				productService.findPageType(pageNum, pageSize, typeName));
		mav.addObject("typeName", typeName);
		return mav; // 省代码(视图解析器)
	}
	
	@DeleteMapping("/deleteType")
	@ResponseBody // ajax提交时必须需要加的注解
	public void deleteTypeAll(@RequestBody String idsStr) {
		System.out.println(idsStr);
		String[] list=idsStr.split(",");
		if(list.length!=0){
			for (String string : list) {
				productService.deleteTypeAll(string);
			}
		}
	}
	
	@GetMapping("/updateType/{id}")
	public ModelAndView updateType(@PathVariable("id") String id){
		ProductType productType=productService.findTypeInfo(id);
		ModelAndView mav=new ModelAndView("/product/updateType.html");
		mav.addObject("list", productType);
		return mav;
	}
	
	@PostMapping("/updateType/{id}")
	@ResponseBody
	public AjaxVo updateType(@Valid ProductTypeVo productTypeVo,BindingResult result,String product_type_id){
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				return new AjaxVo().setErrorCode("10002").setErrorMsg(error.getDefaultMessage());
			}
		}
		
		ProductType pt=new ProductType();
		pt.setId(productTypeVo.getId());
		pt.setTypeName(productTypeVo.getTypeName());
		pt.setTypeInfo(productTypeVo.getTypeInfo());
		productService.updateType(pt);
		return new AjaxVo().setErrorCode("0").setErrorMsg("修改成功");
	}
}
